//
//  HMReadView.m
//  ReadDemo
//
//  Created by YPShao on 2017/10/18.
//  Copyright © 2017年 YPShao. All rights reserved.
//

#import "HMReadView.h"
#import "HMLayoutManager.h"

@implementation HMReadView

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

- (instancetype)initWithFrame:(CGRect)frame {
    if (self == [super initWithFrame:frame])
    {
        [self initReadView];
    }
    return self;
}

- (void)initReadView
{
    CGRect textViewRect = CGRectInset(self.bounds, 10.0, 20.0);
    // NSTextContainer
    NSTextContainer *container = [[NSTextContainer alloc] initWithSize:CGSizeMake(textViewRect.size.width, CGFLOAT_MAX)]; // new in iOS 7.0
    container.widthTracksTextView = YES;
    // NSLayoutManager
    HMLayoutManager *layoutManager = [[HMLayoutManager alloc] init]; // new in iOS 7.0
    [layoutManager addTextContainer:container];
    // NSTextStorage subclass
    NSTextStorage *textStorage = [[NSTextStorage alloc] init]; // new in iOS 7.0
    [textStorage addLayoutManager:layoutManager];
    UITextView *newTextView = [[UITextView alloc] initWithFrame:textViewRect textContainer:container];
    newTextView.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;
    newTextView.font = [UIFont  systemFontOfSize:18];
    self.textView = newTextView;
    [self addSubview:self.textView];
}


- (void)setHighLightRange:(NSRange)highLightRange
{
    NSMutableAttributedString *attrString = self.textView.textStorage;
    [attrString removeAttribute:NSBackgroundColorAttributeName range:NSMakeRange(0, attrString.length)];
    if (NSMaxRange(highLightRange) > attrString.length) {
        return;
    }
    [attrString addAttribute:NSBackgroundColorAttributeName value:[UIColor redColor] range:highLightRange];
}
@end
